<template>
  <div>
    <BasicTable
      @register="registerTable"
      size="small"
      :title="mode == 'task' ? '安全生产检查工作' : '隐患治理工作检查'"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 390px)' }"
    >
      <template #toolbar>
        <a-button @click="exportData">导出记录表格</a-button>
        <a-button type="primary" @click="exportReport">生成并导出报告</a-button>
      </template>
      <template #form-tm="{ model, field }">
        <a-radio-group
          v-model:value="choosetmType"
          style="margin: 0 5px 5px 0"
          button-style="solid"
          @change="changeChooseTm"
        >
          <a-radio-button value="1">本月</a-radio-button>
          <!-- <a-radio-button value="3">本季度</a-radio-button> -->
          <a-radio-button value="4">本年</a-radio-button>
          <a-radio-button value="5">自定义</a-radio-button>
        </a-radio-group>
        <a-range-picker
          v-show="choosetmType == '5'"
          v-model:value="model[field]"
          valueFormat="YYYY-MM-DD"
          :allowClear="false"
        />
      </template>
      <template #plantm="{ record }">
        <div>
          <a-tag
            color="#cd201f"
            v-if="
              record.hasfinish === false &&
              record.hasend === false &&
              moment(record.planendtm).isBefore(moment().format('YYYY-MM-DD HH:mm:ss'))
            "
          >
            已超时</a-tag
          >
          <a-tag
            color="#f50"
            v-else-if="
              record.hasfinish === false &&
              record.hasend === false &&
              moment(record.planendtm).diff(moment().format('YYYY-MM-DD HH:mm:ss'), 'day') <= 7
            "
            >即将超时</a-tag
          >
          {{
            moment(record.planbegintm).format('YYYY-MM-DD') +
            '~' +
            moment(record.planendtm).format('YYYY-MM-DD')
          }}
        </div>
      </template>
      <template #catname="{ record }">
        <Icon
          color="#1677ffbf"
          style="font-size: 15px"
          :icon="
            taskTypeOptions.filter((item) => item.label == record.catname)[0]?.icon ??
            'ant-design:safety-certificate-outlined'
          "
        ></Icon>
        {{ record.catname }}
      </template>
      <template #status="{ record, text, column }">
        <a-tag v-if="record.hasend === true" color="red">终止取消</a-tag>
        <a-tag v-else-if="record.hasfinish === true" color="green">已完成</a-tag>
        <a-tag v-else-if="record.hasfinish === false" color="orange">执行中</a-tag>
      </template>
      <template #transInfo="{ record }">
        <div style="display: flex; flex-wrap: nowrap; justify-content: center">
          <div class="transInfo">
            <div>
              <span v-if="record?.transdeptid <= 0 || record?.transdeptid === record.resdeptid">{{
                record.resdeptname
              }}</span>
              <span v-else-if="record?.transdeptid > 0 && record?.transdeptid !== record.resdeptid"
                >{{ record.resdeptname }}→{{ record.transdeptname }}</span
              >
            </div>

            <div>
              <span
                v-if="
                  record?.transuserid === null ||
                  record?.transuserid === 0 ||
                  record?.transuserid === record.resuserid1 ||
                  record?.transuserid === record.resuserid2
                "
                >{{
                  (record.resusername1 ?? '') +
                  (record.resuserid2 !== null && record.resuserid2 !== 0 && record.resusername2
                    ? ',' + record.resusername2
                    : '')
                }}</span
              >
              <span
                v-else-if="
                  record?.transuserid !== null &&
                  record?.transuserid > 0 &&
                  record?.transuserid !== record.resuserid2 &&
                  record?.transuserid !== record.resuserid1
                "
                >{{
                  (record.resusername1 ?? '') +
                  (record.resuserid2 !== null && record.resuserid2 !== 0 && record.resusername2
                    ? ',' + record.resusername2
                    : '')
                }}→{{ record.transusername ?? '' }}</span
              >
            </div>
          </div>
          <div class="transState">
            <a-tag
              v-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === false &&
                !record.transreceivetm
              "
              >未接收</a-tag
            >
            <a-tag
              color="success"
              v-else-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === true &&
                record.transreceivetm
              "
              >已接收</a-tag
            >
            <a-tag
              color="error"
              v-else-if="
                (record.transdeptid !== 0 || record.transuserid !== 0) &&
                record.transhasreceive === false &&
                record.transreceivetm
              "
              >已拒收</a-tag
            >
          </div>
        </div>
        <!-- 如当前责任部门为空或当前责任部门与责任部门相同时，显示责任部门名称； -->
        <!-- 如当前责任部门不为空切与责任部门不同时，显示为：责任部门名称→当前责任部门； -->
      </template>
      <template #ismajor="{ record }">
        <a-tag :color="record.ismajor ? '#cd201f' : '#3b5999'">{{
          record.ismajor ? '重大' : '一般'
        }}</a-tag>
      </template>
      <template #boolSlot="{ record, text, column }">
        <a-tag :color="text == true ? 'red' : 'green'">{{ text == true ? '是' : '否' }}</a-tag>
      </template>
      <template #troublestatus="{ record, text, column }">
        <a-tag color="red" v-if="!record.hasdispatch">未派单</a-tag>
        <a-tag color="orange" v-else-if="record.hasdispatch && !record.hascorrect">整改中</a-tag>
        <a-tag
          color="yellow"
          v-else-if="record.hasdispatch && record.hascorrect && !record.hascheck"
          >待验收</a-tag
        >
        <a-tag color="green" v-else-if="record.hasdispatch && record.hascorrect && record.hascheck"
          >已验收</a-tag
        >
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              label: '报告',
              onClick: onRecordButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, watch, unref, computed, onMounted, ref } from 'vue';
  import { categoryTableColumns, categoryConditionFormSchema } from './dict.data';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { getUserOrganization } from '/@/api/ehs/organization';
  import {
    ehsRecordConditionFormSchema,
    todoTaskListColumns,
    troubleCorrectListColumns,
  } from './ehsReport.data';
  import {
    queryInspection,
    generateInspectionReport,
    queryTroubleCorrect,
    generateTroubleCorrectReport,
  } from '/@/api/ehs/ehsReport';
  import { reportEhsTroubleCorrect } from '/@/api/ehs/troubleCorrect';
  import { reportEhsTask } from '/@/api/ehs/taskItem';
  import { getOrgDeptTree } from '/@/api/ehs/organization';
  import { getAllTaskCategory } from '/@/api/ehs/taskCategory';
  import * as XLSX from 'xlsx';
  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  import { getFileApi } from '/@/api/platform/file';
  const { uploadUrl } = useGlobSetting();
  const { globalProjectCode } = useGlobSetting();
  export default defineComponent({
    name: 'ehsReportIndex',
    components: { BasicTable, TableAction },
    emits: [],
    props: ['mode'],
    setup(props, { emit }) {
      const choosetmType = ref('4');
      const taskTypeOptions = ref([]);
      const projectCode = ref<String>(globalProjectCode);
      const organizationCode = ref();
      const searchFormValue = ref({});
      const [registerTable, { reload, getForm, setLoading }] = useTable({
        api: props.mode == 'task' ? queryInspection : queryTroubleCorrect,
        immediate: false,
        columns: props.mode == 'task' ? todoTaskListColumns : troubleCorrectListColumns,
        canResize: true,
        showTableSetting: true,
        tableSetting: {
          redo: false,
        },
        showIndexColumn: true,
        useSearchForm: true,
        formConfig: {
          autoAdvancedLine: 1,
          fieldMapToTime: [['tm', ['begintm', 'endtm'], 'YYYY-MM-DD']],
          labelWidth: 90,
          schemas: ehsRecordConditionFormSchema,
          actionColOptions: {
            span: 24,
          },
        },
        beforeFetch: (params) => {
          params.orgcode = organizationCode.value;
          searchFormValue.value = params;
          return params;
        },
        afterFetch: (data) => {
          let tmp = [];
          if (data) {
            if (props.mode == 'task') {
              data?.forEach((item) => {
                let value = {
                  itemname: item.itemname,
                  plantm:
                    moment(item.planbegintm).format('YYYY-MM-DD') +
                    '~' +
                    moment(item.planendtm).format('YYYY-MM-DD'),
                  unitname: item.unitname,
                  plancount: (item.execcount ?? '-') + '/' + (item.planfrequencycount ?? '-'),
                  status:
                    item.hasend === true ? '已完成' : item.hasfinish === true ? '已完成' : '执行中',
                  execendtm: item.execendtm,
                  resusername:
                    item.resdeptname +
                    ' / ' +
                    item.resusername1 +
                    (item.resusername2 ? ',' + item.resusername2 : ''),
                };
                tmp.push(value);
              });
              tmp.unshift([
                '任务项名称',
                '计划时间',
                '单元',
                '执行次数/计划次数',
                '任务状态',
                '完成时间',
                '责任部门/责任人',
              ]);
            } else {
              if (data)
                data?.forEach((item) => {
                  let value = {
                    title: item.title,
                    tm: item.tm,
                    unit: item.unit,
                    ismajor: item.ismajor ? '是' : '否',
                    status: !item.hasdispatch
                      ? '未派单'
                      : item.hasdispatch && !item.hascorrect
                      ? '整改中'
                      : item.hasdispatch && item.hascorrect && !item.hascheck
                      ? '待验收'
                      : '已验收',
                  };
                  tmp.push(value);
                });
              tmp.unshift(['标题', '上报/发现时间', '单元', '是否重大', '状态']);
            }
            ledgerData = tmp.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });
          }

          return data;
        },
        striped: false,
        bordered: true,
        ellipsis: true,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      function changeChooseTm(e) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          3: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        if (e.target.value != '5') {
          getForm().setFieldsValue({
            tm: op[e.target.value],
          });
        }
        getForm().clearValidate();
      }

      function afterSuccess() {
        reload();
      }

      function openReport(id) {
        window.open(uploadUrl + getFileApi + id);
      }

      function onRecordButtonClick(record) {
        if (props.mode == 'task') {
          if (record.rptid <= 0) {
            reportEhsTask(record.itemid).then((res) => {
              if (res) {
                createMessage.success('重新生成报告成功');
                openReport(res);
              } else {
                createMessage.error('重新生成报告失败');
              }
            });
          } else {
            openReport(record.rptid);
          }
        } else {
          if (record.rptid <= 0) {
            reportEhsTroubleCorrect(record.correctid).then((res) => {
              if (res) {
                createMessage.success('重新生成报告成功');
                openReport(res);
              } else {
                createMessage.error('重新生成报告失败');
              }
            });
          } else {
            openReport(record.rptid);
          }
        }
      }

      //需要导出的数组数据
      let ledgerData = [];
      // 表格数据导出
      function exportData() {
        const filename = `安全生产检查工作.xlsx`; //导出文件名
        const worksheet_name = 'Sheet1'; // Excel第一个sheet的名称
        const workbook = XLSX.utils.book_new(); //创建一个新的workbook
        const worksheet = XLSX.utils.aoa_to_sheet(ledgerData);
        console.log(ledgerData, 'ledgerData');
        worksheet['!merges'] = [];
        //列宽设置
        worksheet['!cols'] = [
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
        ];
        //保存数据信息并下载文件
        XLSX.utils.book_append_sheet(workbook, worksheet, worksheet_name); //将数据添加到工作簿
        XLSX.writeFile(workbook, filename); //下载excel文件
      }

      function exportReport() {
        setLoading(true);
        if (props.mode == 'task') {
          generateInspectionReport(searchFormValue.value).then((res) => {
            if (res) {
              createMessage.success('生成报告成功');
              let url = window.URL.createObjectURL(
                new Blob([res], {
                  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                }),
              );
              window.open(url, '_blank');
            } else {
              createMessage.error('生成报告失败');
            }
            setLoading(false);
          });
        } else {
          generateTroubleCorrectReport(searchFormValue.value).then((res) => {
            if (res) {
              createMessage.success('生成报告成功');
              let url = window.URL.createObjectURL(
                new Blob([res], {
                  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                }),
              );
              window.open(url, '_blank');
            } else {
              createMessage.error('生成报告失败');
            }
            setLoading(false);
          });
        }
      }

      onMounted(() => {
        //  获取枚举类
        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          getAllTaskCategory(res.orgcode).then((res3) => {
            taskTypeOptions.value = res3
              ? res3?.map((option) => {
                  return {
                    label: option.catname,
                    value: option.catcode,
                    icon: option.icon,
                  };
                })
              : [];
          });
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: res.orgcode,
          }).then((res2) => {
            getOrgDeptTree(res.orgcode).then((res3) => {
              getForm().updateSchema([
                {
                  field: 'deptid',
                  componentProps: {
                    treeData: res3,
                    treeDefaultExpandAll: true, //默认展开
                    listHeight: 220,
                    getPopupContainer: (triggerNode) => document.body,
                    fieldNames: { label: 'title', value: 'key', children: 'children' },
                  },
                },
                {
                  field: 'unitid',
                  componentProps: {
                    treeData: res2,
                    treeDefaultExpandAll: true, //默认展开
                    listHeight: 220,
                    getPopupContainer: (triggerNode) => document.body,
                    fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                  },
                },
                {
                  field: 'category',
                  ifShow: props.mode == 'task',
                },
              ]);
            });
          });
          organizationCode.value = res?.orgcode;
          reload();
        });
        queryEnumOptions('EhsTaskCategoryTypeEnum').then((res) => {
          getForm().updateSchema([
            {
              field: 'category',
              componentProps: {
                mode: 'multiple',
                options: res[0].options?.map((option) => {
                  return {
                    value: Number(option.key),
                    label: option.value,
                  };
                }),
              },
            },
          ]);
        });
      });
      return {
        moment,
        taskTypeOptions,
        organizationCode,
        registerTable,
        afterSuccess,
        changeChooseTm,
        onRecordButtonClick,
        choosetmType,
        exportData,
        exportReport,
      };
    },
  });
</script>
<style scoped>
  /* :deep(.ant-row) {
    justify-content: space-between !important;
  } */
</style>
